package com.bright.hxj.qchz.util;

//import jdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptEngineUtil {

    private static ScriptEngineManager manager = null;
    private static ScriptEngine engine = null;

//    public static Object eval(String script) throws ScriptException {
//        return engine.eval(script);
//    }

    public static ScriptEngine getEngine() throws ScriptException {
        if (manager == null || engine == null) {
            manager = new ScriptEngineManager();
            engine = manager.getEngineByName("javascript");

            engineReady();
        }
        return engine;
    }

    // 初始时让js引擎拥有的函数
    private static void engineReady() throws ScriptException {
//        engine.eval("function test() {}");
    }

    public static Object invokeFunction(String functionName, Object... args) throws ScriptException, NoSuchMethodException {
        return ((Invocable) engine).invokeFunction(functionName, args);
    }


    public static void test(String[] args) throws ScriptException {
//        ScriptEngineManager manager = new ScriptEngineManager();
//        ScriptEngine engine = manager.getEngineByName("javascript");
        getEngine();

        // 执行JavaScript代码
        try {
//            engine.eval("print('Hello, World!')");
//            engine.put("a", 1);
//            engine.put("b", 2);
//            Object eval = engine.eval("a == b");
//            System.out.println(eval);
//            eval = engine.eval("a < b + 5");
//            System.out.println(eval);
//            Map<String, Object> map = new HashMap<>();
//            map.put("fz01", 50);
//            Map<String, Object> subMap = new HashMap<>();
//            subMap.put("zc_zms", 100);
//            map.put("zc01", subMap);
//            engine.put("d", map);
//            engine.eval("print(d);");
//            engine.eval("print(d.zc01.zc_zms);");
//            engine.eval("function test(x, y) {print(x+2);print(y+'b');return x==1;}");
//            Object o = ((Invocable) engine).invokeFunction("test", 1, "a");
//            System.out.println(o);
            engine.put("a", 1.79);
            engine.put("b", 0.12);
            System.out.println(engine.eval("a+b"));
            System.out.println(1.79+0.12);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
